const express = require('express');  
const router = express.Router();  
const bcrypt = require('bcryptjs');
const { User } = require('../models'); // 确保正确导入 User 模型  
const { failure, success } = require('../utils/responses')


// 注册接口  
router.post('/', async (req, res) => {  
  try {  
    const {username, phone, password} = {
      username:req.body.username,
      phone:req.body.phone,
      password:req.body.password,
      sex:2,
      role:0,
    }
    // 验证输入数据  
    if (!username || !phone  || !password) {  
      return res.status(400).json({ message: '所有字段都是必填的' });  
    }  

    // 检查用户名是否已存在  
    
    const existingUser = await User.findOne({ where: { phone } });
    if (existingUser) {  
      return res.status(409).json({ message: '此手机号已注册' });  
    }  
    console.log("Before hashing"); 
    // 哈希密码  
    const hashedPassword = await bcrypt.hash(password, 10); // 10 表示盐的轮数  
    console.log("After hashing"); 
    // 创建新用户  
    const newUser = await User.create({  
      username,  
      phone,   
      password: hashedPassword, 
      sex:2,
      role:0
    }); 
    delete newUser.dataValues.password;
    success(res,'注册成功', {newUser},201)
  } catch (error) {  
    failure(res, error)
  }  
});  

module.exports = router;  